package cn.ronghuanet.auth.controller;

import cn.ronghuanet.auth.context.LoginContext;
import cn.ronghuanet.auth.dto.LoginDto;
import cn.ronghuanet.base.utils.AjaxResult;
import cn.ronghuanet.org.domain.Employee;
import cn.ronghuanet.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class AuthController {

    @Autowired
    private IEmployeeService employeeService;

    @PostMapping
    public AjaxResult login(@RequestBody LoginDto loginDto){
        Employee employee = employeeService.queryByUsername(loginDto.getUsername());
        if (employee!=null){
            if (employee.getPassword().equals(loginDto.getPassword())) {
                //登录成功
                //生成token[唯一不重复]
                String token = UUID.randomUUID().toString();
                //employee做脱敏处理
                employee.setPassword("");
                //往全局map里面存放数据
                LoginContext.context.put(token,employee);
                //组装返回到前端的数据[token,当前的登录用户]
                Map<String,Object> map = new HashMap<>();
                map.put("token",token);
                map.put("user",employee);
                //登录失败 密码错误
                return AjaxResult.me().setData(map);
            }else {
                //登录失败 密码错误
                return AjaxResult.me().setSuccess(false).setMsg("用户或密码错误");
            }

        }else {//根据用户名没有找到对应的用户
            //登录失败 密码错误
            return AjaxResult.me().setSuccess(false).setMsg("用户或密码错误");
        }

    }
}
